import {computed, defineComponent, h, resolveComponent} from 'vue';

export default defineComponent({
  name: 'FxIcon',
  inheritAttrs: false,
  props: {
    // 类
    class: {
      type:  [String,Object]
    },
    // 样式
    style: {
      type: [String,Object]
    },
    // 图标的名称
    name: {
      type: String,
      required: true
    },
    // 图标的名称
    size: {
      type: [Number, String]
    },
    // 大小
    viewBox: {
      type: String
    }
  },
  emits: [],
  setup: function (props, context) {

    const renderSymbol = () => {
      const viewBox = props.viewBox || '0 0 128 128';
      const innerHTML = '<svg aria-hidden="true" viewBox="' + viewBox + '" xmlns="http://www.w3.org/2000/svg">' +
        '<use xlink:href="#' + props.name + '"/>' +
        '</svg>';
      return h('i', {
        class: ['fx-icon', props.class],
        style: [symbolStyle.value, props.style],
        innerHTML: innerHTML,
        ...context.attrs
      });
    };
    const renderImage = () => {
      return h('i', {
        class: ['fx-icon', props.class],
        style: [imageStyle.value, props.style],
        ...context.attrs
      }, [
        h('img', {
          src: props.name,
          alt: '',
          ...context.attrs
        })
      ]);
    };
    const renderClass = () => {
      let className = props?.name;
      if (className.startsWith('class-')) {
        className = className.substring(6);
      }
      return h('div', {
        class: ['fx-icon', props.class],
        style: [props.style],
        ...context.attrs
      }, h('div', {
        class: className
      }));
    };
    const renderComponent = () => {
      return h(resolveComponent('NIcon'), {
        class: ['fx-icon', props.class],
        style: props.style,
        size: props.size,
        ...context.attrs
      }, {
        default: () => h(resolveComponent(props.name), {})
      });
    };

    const isSymbolIcon = computed(() => {
      return props?.name?.startsWith('fx-icon-');
    });
    const isClassIcon = computed(() => {
      return props?.name?.startsWith('fx-class-') ||
        props?.name?.startsWith('class-');
    });
    const isImageIcon = computed(() => {
      const linesString = ['https://', 'http://', '/src/', '/assets/', 'data:image', '/static/'];
      return linesString.find((str) => props.name?.startsWith(str));
    });
    const symbolStyle = computed(() => {
      return `font-size: ${props.size}px;`;
    });
    const imageStyle = computed(() => {
      return `width: ${props.size}px;height: ${props.size}px;display: inline-block;overflow: hidden;`;
    });

    return () => {
      return isSymbolIcon.value ? renderSymbol() :
        isImageIcon.value ? renderImage() :
          isClassIcon.value ? renderClass() : renderComponent();
    };
  }
});